/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.kcrx.autoweightapp.utils

import android.os.CountDownTimer
import android.view.View
import android.widget.Button

/**
 * * 构造方法
*@Params:
*@button – 需要显示倒计时的Button
*@countDownTime – 倒计时总时间,单位是秒
 */
class AutoAcceptButtomHelper(private val button: Button,private val delay:Int) {
    private val interval=1
    var autoAcceptTimer:CountDownTimer?=null
    var acceptListener: AutoAcceptListener?=null

    /***
     * 初始化计时器
     */
    fun initAutoTimer(){
        val buttonText=button.text
     if(autoAcceptTimer==null){
         autoAcceptTimer=object :CountDownTimer((delay*1000).toLong(),(interval*1000).toLong()){
             override fun onTick(time: Long) {
                 // 第一次调用会有1-10ms的误差，因此需要+15ms，防止第一个数不显示，第二个数显示2s
                 val surplusTime = ((time + 15) / 1000)
                 acceptListener?.onTick(surplusTime.toInt())
                     button.text="自动确认剩余:$surplusTime S"
             }
             override fun onFinish() {
                 if(button.isEnabled){
                     button.performClick()//自动按下
                 }
                 acceptListener?.let {
                     it.onFinish()
                 }
                 button.isEnabled=false
                 button.text=buttonText
             }
         }
     }
    }

    /***
     * 开始倒计时
     */
    fun start(){
        initAutoTimer()
        button.isEnabled=true
        autoAcceptTimer?.start()
    }

    /***
     * 设置倒计时监听器
     */
    fun setAutoAccepterListener(autoAcceptListener: AutoAcceptListener):AutoAcceptButtomHelper{
        acceptListener=autoAcceptListener
        return this
    }

    /***
     * 取消倒计时
     */
   fun cancel(){
        autoAcceptTimer?.onFinish()
        autoAcceptTimer?.cancel()
   }

    /***
     *回收资源
     */
    fun recycle(){
        cancel()
        autoAcceptTimer=null
    }
    interface AutoAcceptListener{
        fun onTick(time:Int)
        fun onFinish()
    }
}